package com.hezhi.project.module.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hezhi.common.utils.DateUtils;
import com.hezhi.framework.web.controller.BaseController;
import com.hezhi.framework.web.domain.AjaxResult;
import com.hezhi.project.module.abnormal.domain.Abnormal;
import com.hezhi.project.module.abnormal.service.IAbnormalService;
import com.hezhi.project.module.inOut.domain.InOut;
import com.hezhi.project.module.inOut.domain.KafKaMsgJxt;
import com.hezhi.project.module.inOut.service.IInOutService;
import com.hezhi.project.module.machineRecord.domain.MachineRecord;
import com.hezhi.project.module.machineRecord.service.IMachineRecordService;
import com.hezhi.project.module.parameter.domain.Parameter;
import com.hezhi.project.module.parameter.service.IParameterService;
import com.hezhi.project.module.parent.domain.Parent;
import com.hezhi.project.module.parent.service.IParentService;
import com.hezhi.project.module.student.domain.Student;
import com.hezhi.project.module.student.service.IStudentService;
import com.hezhi.project.weixin.utils.TemplateUtils;
import com.hezhi.project.weixin.utils.WeChatUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * api接口类
 * 
 * @author 徐伦
 *
 */
@Controller
@Slf4j
@RequestMapping("/api")
public class APIController extends BaseController {

	@Autowired
	private IStudentService studentService;
	@Autowired
	private IInOutService inOutService;
	@Autowired
	private IAbnormalService abnormalService;
	@Autowired
	private IParameterService parameterService;
	@Autowired
	private IMachineRecordService machineRecordService;
	@Autowired
	private IParentService parentService;

	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	/**
	 * 进出记录提交接口
	 * 
	 * @param inOut
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/inout")
	public AjaxResult inOut(@RequestBody List<InOut> list, HttpServletRequest request) {
		if (list.size() > 0) {
			StringBuffer msg = new StringBuffer();
			for (InOut inOut : list) {
				if (inOut.getIcNumber() == null || "".equals(inOut.getIcNumber())) {
					msg.append("IC卡号不能为空");
					continue;
				} else if (inOut.getInOutFlag() == null || "".equals(inOut.getInOutFlag())) {
					msg.append("卡号[" + inOut.getIcNumber() + "]进出标识不能为空;");
					continue;
				} else if (inOut.getInOutTime() == null || "".equals(inOut.getInOutTime())) {
					msg.append("卡号[" + inOut.getIcNumber() + "]进出时间不能为空;");
					continue;
				} else if ("01".indexOf(inOut.getInOutFlag()) == -1) {
					msg.append("卡号[" + inOut.getIcNumber() + "]进出标识参数错误;");
					continue;
				} else if (inOut.getInOutTime().getTime() - new Date().getTime() > 1000 * 60 * 10) {
					msg.append("卡号[" + inOut.getIcNumber() + "]参数错误：进出时间超前10分钟;");
					continue;
				} else {
					// 业务处理
					// 1、根据IC卡号获取学生信息
					// 2、判断学生信息是否为空 为空则返回错误
					// 3、 保存数据到进出记录表中
					// 4、进--》判断是否有当天记录 有--如果出校记录有值则清空出校时间 无 --新增异常表记录
					// 5、出--》判断是否有当天记录 有--修改异常表中出校时间 无 --异常出校
					// StudentIc studentIc =
					// studentIcService.selectStudentIcByIcNumber(inOut.getIcNumber());
					Student student = new Student();
					student.getStudentIc().setIcNumber(inOut.getIcNumber());
					student.getStudentIc().setStatus("1");
					student.setStatus("1");
					List<Student> listStudent = studentService.selectStudentList(student);
					if (listStudent.size() == 1) {
						student = listStudent.get(0);
						inOut.setInOutDate();
						inOut.setInOutTimeStr();
						inOutService.saveInOut(inOut);
						Abnormal abnormal = new Abnormal();
						abnormal.setStudentNumber(student.getStudentNumber());
						abnormal.setInOutDate(inOut.getInOutDate());
						abnormal.setClassNumber(student.getClassNumber());
						abnormal.setInOutFlag(inOut.getInOutFlag());
						// 查询是否有异常记录
						// List<Abnormal> listAbnormal = abnormalService.selectAbnormalList(abnormal);
						abnormal.setInOutTime(inOut.getInOutTimeStr());
						abnormal.setInOutId(inOut.getInOutId());
						abnormal.setUrl(inOut.getUrl());
						abnormal = setStatus(abnormal);// 设置进出状态
						int abnormalId = abnormalService.saveAbnormal(abnormal);
						sendMessage(request, student, abnormal, abnormalId);
					} else if (listStudent.size() == 0) {
						msg.append("卡号[" + inOut.getIcNumber() + "]参数错误：未找到对应学生;");
					} else {
						msg.append("卡号[" + inOut.getIcNumber() + "]系统错误;");
					}
				}
			}
			return success(msg.toString());
		} else {
			return error(2, "参数错误：参数为空;");
		}
	}

	/**
	 * 进出记录提交接口
	 * 
	 * @param inOut
	 * @return
	 */
	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping("/inout2") public AjaxResult inOut2(HttpServletRequest
	 * request){ AjaxResult json = new AjaxResult(); StringBuffer sb = new
	 * StringBuffer(); BufferedReader br; try { br = new BufferedReader( new
	 * InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
	 * String temp; while ((temp = br.readLine()) != null) { sb.append(temp); }
	 * br.close(); System.out.println(sb.toString()); } catch
	 * (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException
	 * e) { e.printStackTrace(); } json.put("message", "提交失败"); json.put("status",
	 * 0); return json; }
	 */

	/**
	 * 设置异常
	 * 
	 * @param abnormal
	 * @return
	 */
	public Abnormal setStatus(Abnormal abnormal) {
		Parameter parameter = parameterService.getParameter();
		if ("0".equals(abnormal.getInOutFlag())) {
			// 进
			if (!DateUtils.betweenTime(parameter.getInSTime(), abnormal.getInOutTime())) {
				abnormal.setStatus("2");
				abnormal.setRemarks(parameter.getInSTime() + "前入校");
			} else if (DateUtils.betweenTime(parameter.getInETime(), abnormal.getInOutTime())) {
				abnormal.setStatus("3");
				abnormal.setRemarks(parameter.getInETime() + "后入校");
			} else {
				abnormal.setStatus("0");
				abnormal.setRemarks(parameter.getInSTime() + "至" + parameter.getInETime() + "入校");
			}
		} else {
			// 出
			if (!DateUtils.betweenTime(parameter.getOutSTime(), abnormal.getInOutTime())) {
				abnormal.setStatus("4");
				abnormal.setRemarks(parameter.getOutSTime() + "前出校");
			} else if (DateUtils.betweenTime(parameter.getOutETime(), abnormal.getInOutTime())) {
				abnormal.setStatus("5");
				abnormal.setRemarks(parameter.getOutETime() + "后出校");
			} else {
				abnormal.setStatus("0");
				abnormal.setRemarks(parameter.getOutSTime() + "至" + parameter.getOutETime() + "出校");
			}
		}
		return abnormal;
	}

	/**
	 * 学生卡号信息下发状态回调接口
	 * 
	 * @param list
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/studentstatus")
	public AjaxResult studentstatus(@RequestBody List<MachineRecord> list) {
		if (list.size() == 0) {
			return error(2, "参数错误：参数为空");
		} else {
			for (MachineRecord machineRecord : list) {
				machineRecordService.saveMachineRecord(machineRecord);
			}
		}
		return success();
	}

	/**
	 * 发送进出校通知
	 * 
	 * @param student
	 * @param abnormal
	 */
	public void sendMessage(HttpServletRequest request, Student student, Abnormal abnormal, int abnormalId) {
		Parent parent = new Parent();
		parent.setStudentNumber(student.getStudentNumber());
		List<Parent> list = parentService.selectParentList(parent);
		if (list.size() > 0) {
			for (Parent p : list) {
				if (p.getOpenId() != null) {
					Map<String, Object> map = new HashMap<>();
					switch (abnormal.getStatus()) {
					case "1":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子未入校园\",\"color\":\"#173177\"}"));
						break;
					case "2":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子提前入校\",\"color\":\"#173177\"}"));
						break;
					case "3":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子迟到\",\"color\":\"#173177\"}"));
						break;
					case "4":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子提前出校园\",\"color\":\"#173177\"}"));
						break;
					case "5":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子出校超时\",\"color\":\"#173177\"}"));
						break;
					case "6":
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子未出校园\",\"color\":\"#173177\"}"));
						break;
					default:
						map.put("first", JSONObject.parseObject("{\"value\":\"家长您好，您的孩子正常出入校园\",\"color\":\"#173177\"}"));
						break;
					}
					map.put("keyword1", JSONObject.parseObject("{\"value\":\"" + student.getName() + "\",\"color\":\"#173177\"}"));
					if ("0".equals(abnormal.getInOutFlag())) {
						map.put("keyword2", JSONObject.parseObject("{\"value\":\"进校\",\"color\":\"#173177\"}"));
					} else {
						map.put("keyword2", JSONObject.parseObject("{\"value\":\"出校\",\"color\":\"#173177\"}"));
					}
					map.put("keyword3", JSONObject.parseObject("{\"value\":\"" + abnormal.getInOutDate() + " " + abnormal.getInOutTime() + "\",\"color\":\"#173177\"}"));
					map.put("remark", JSONObject.parseObject("{\"value\":\"点击详情可查看现场图文信息。\",\"color\":\"#173177\"}"));
					String url = WeChatUtils.getProjectPath(request) + "/weixin/inoutInfo?abnormalId=" + abnormalId;
					TemplateUtils.send(p.getOpenId(), TemplateUtils.INOUTSCHOOL, url, map);
					
					//提交到kafka
					try {
						KafKaMsgJxt msgKfk = new KafKaMsgJxt().setTemplateId(TemplateUtils.INOUTSCHOOL).setUrl(url).setParams(map).setOpenId(p.getOpenId());
						msgKfk.setAppId("wx7a917b3b518e0deb");//和智科技
						this.kafkaTemplate.send("jxt", JSONObject.toJSONString(msgKfk));	
					}catch(Exception e) {
						log.error("提交到kafka消息异常",e);
					}
				}
			}
		}
	}

}
